package com.example.springboot2.service;

import com.example.springboot2.dto.LoginRequest;
import com.example.springboot2.dto.LoginResponse;
import com.example.springboot2.dto.RegisterRequest;
import com.example.springboot2.entity.User;
import com.example.springboot2.exception.BusinessException;
import com.example.springboot2.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 认证服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthService {

    private final AuthenticationManager authenticationManager;
    private final UserService userService;
    private final JwtUtil jwtUtil;

    /**
     * 用户登录
     */
    public LoginResponse login(LoginRequest request) {
        try {
            // 进行身份验证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())
            );

            User user = (User) authentication.getPrincipal();
            
            // 生成JWT token
            String token = jwtUtil.generateToken(user.getUsername(), user.getId(), user.getRole().name());
            
            // 更新登录信息
            userService.updateLoginInfo(user.getId(), request.getLoginIp());
            
            return LoginResponse.builder()
                    .token(token)
                    .userInfo(LoginResponse.UserInfo.builder()
                            .id(user.getId())
                            .username(user.getUsername())
                            .name(user.getName())
                            .email(user.getEmail())
                            .phone(user.getPhone())
                            .avatar(user.getAvatar())
                            .role(user.getRole().name().toLowerCase())
                            .build())
                    .build();
                    
        } catch (AuthenticationException e) {
            log.warn("用户登录失败: {}", request.getUsername());
            throw new BusinessException(401, "用户名或密码错误");
        }
    }

    /**
     * 用户注册
     */
    @Transactional
    public void register(RegisterRequest request) {
        // 创建用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword());
        user.setName(request.getName());
        user.setEmail(request.getEmail());
        user.setPhone(request.getPhone());
        user.setRole(User.UserRole.MERCHANT); // 默认为商家角色
        
        userService.createUser(user);
        
        log.info("用户注册成功: {}", request.getUsername());
    }

    /**
     * 修改密码
     */
    @Transactional
    public void changePassword(Long userId, String oldPassword, String newPassword) {
        userService.changePassword(userId, oldPassword, newPassword);
        log.info("用户修改密码成功: {}", userId);
    }

    /**
     * 重置密码
     */
    @Transactional
    public void resetPassword(String username, String newPassword, String verifyCode) {
        // TODO: 验证验证码
        // 这里应该验证验证码的有效性
        
        userService.resetPassword(username, newPassword);
        log.info("用户重置密码成功: {}", username);
    }

    /**
     * 发送验证码
     */
    public void sendVerifyCode(String phone) {
        // TODO: 实现发送验证码逻辑
        // 这里应该调用短信服务发送验证码
        log.info("发送验证码到手机: {}", phone);
    }

    /**
     * 刷新token
     */
    public String refreshToken(String oldToken) {
        try {
            String username = jwtUtil.getUsernameFromToken(oldToken);
            User user = userService.findByUsername(username)
                    .orElseThrow(() -> new BusinessException("用户不存在"));
            
            return jwtUtil.generateToken(user.getUsername(), user.getId(), user.getRole().name());
        } catch (Exception e) {
            throw new BusinessException("Token刷新失败");
        }
    }
}
